const sqlite3 = require('../app/backend/node_modules/sqlite3').verbose();
const db = new sqlite3.Database('../app/backend/data/pph.sqlite');

console.log('🧪 测试重算功能的节拍字段分配...');
console.log('=====================================');

async function testRecomputeTakt() {
  return new Promise((resolve, reject) => {
    // 1. 检查当前A0101150004的节拍分配
    console.log('📊 检查A0101150004当前的节拍分配:');
    db.all(`SELECT record_date, line_name, is_whole_machine, 
                   target_takt_time, target_motor_takt_time,
                   CASE WHEN is_whole_machine = 1 THEN target_takt_time 
                        ELSE target_motor_takt_time END as should_display_takt
            FROM pph_records 
            WHERE material_code = 'A0101150004' 
            AND line_name IN ('3', '5', '9', '10')
            ORDER BY record_date DESC, line_name LIMIT 10`, (err, rows) => {
      if (err) {
        console.error('❌ 查询失败:', err);
        return reject(err);
      }
      
      console.table(rows);
      
      // 2. 检查目标值配置
      console.log('\n🎯 检查A0101150004的目标值配置:');
      db.all(`SELECT material_code, line_name, record_date, 
                     takt_time, motor_takt_time, 
                     whole_machine_target, motor_target,
                     is_active
              FROM pph_targets 
              WHERE material_code = 'A0101150004' 
              AND line_name IN ('3', '5', '9', '10')
              AND is_active = 1
              ORDER BY record_date DESC, line_name LIMIT 5`, (err2, targets) => {
        if (err2) {
          console.error('❌ 目标值查询失败:', err2);
          return reject(err2);
        }
        
        console.table(targets);
        
        if (targets.length === 0) {
          console.log('❌ 未找到A0101150004的目标值配置');
          console.log('💡 建议：先在PPH目标值管理中为A0101150004配置目标值');
          db.close();
          return resolve();
        }
        
        // 3. 分析节拍分配逻辑
        console.log('\n🔍 分析节拍分配逻辑:');
        
        const motorRecords = rows.filter(r => r.is_whole_machine === 0);
        const wholeRecords = rows.filter(r => r.is_whole_machine === 1);
        const errorRecords = motorRecords.filter(r => r.target_takt_time !== null);
        
        console.log(`- 电机生产记录: ${motorRecords.length} 条`);
        console.log(`- 整机生产记录: ${wholeRecords.length} 条`);
        console.log(`- 错误的电机记录（有整机节拍）: ${errorRecords.length} 条`);
        
        // 4. 检查目标值配置是否正确
        const targetsByLine = {};
        targets.forEach(t => {
          if (!targetsByLine[t.line_name]) targetsByLine[t.line_name] = [];
          targetsByLine[t.line_name].push(t);
        });
        
        console.log('\n📋 各生产线的目标值配置:');
        Object.keys(targetsByLine).forEach(line => {
          const lineTargets = targetsByLine[line];
          const latest = lineTargets[0]; // 已按日期降序排列
          console.log(`- ${line}号线: 整机节拍=${latest.takt_time}, 电机节拍=${latest.motor_takt_time}`);
          
          if (latest.takt_time == null && latest.motor_takt_time == null) {
            console.log(`  ⚠️ ${line}号线没有配置任何节拍值`);
          } else if (latest.takt_time != null && latest.motor_takt_time != null) {
            console.log(`  ✅ ${line}号线配置了双节拍（整机+电机）`);
          } else if (latest.motor_takt_time != null) {
            console.log(`  ✅ ${line}号线仅配置电机节拍（适合电机生产）`);
          } else {
            console.log(`  ✅ ${line}号线仅配置整机节拍（适合整机生产）`);
          }
        });
        
        // 5. 模拟重算逻辑
        console.log('\n🔄 模拟重算逻辑测试:');
        
        // 测试电机生产记录的节拍分配
        const testMotorRecord = motorRecords[0];
        if (testMotorRecord) {
          const lineTarget = targetsByLine[testMotorRecord.line_name];
          if (lineTarget && lineTarget[0]) {
            const target = lineTarget[0];
            const expectedTaktTime = null; // 电机生产不应该有整机节拍
            const expectedMotorTaktTime = target.motor_takt_time;
            
            console.log(`测试记录: ${testMotorRecord.line_name}号线电机生产`);
            console.log(`- 当前整机节拍: ${testMotorRecord.target_takt_time}`);
            console.log(`- 当前电机节拍: ${testMotorRecord.target_motor_takt_time}`);
            console.log(`- 期望整机节拍: ${expectedTaktTime}`);
            console.log(`- 期望电机节拍: ${expectedMotorTaktTime}`);
            
            const isCorrect = (testMotorRecord.target_takt_time === expectedTaktTime) && 
                             (testMotorRecord.target_motor_takt_time == expectedMotorTaktTime);
            
            if (isCorrect) {
              console.log('✅ 节拍分配正确');
            } else {
              console.log('❌ 节拍分配错误，需要重算');
            }
          }
        }
        
        db.close();
        resolve();
      });
    });
  });
}

// 执行测试
testRecomputeTakt().catch(err => {
  console.error('❌ 测试失败:', err);
  process.exit(1);
});
